from . import web
from flask import render_template, request, redirect, url_for, flash
from flask_login import login_user, logout_user
from app.forms.auth import RegisterForm, LoginForm, EmailForm, ResetPasswordForm
from app.models.user import User
from app.models.base import db
from app.libs.email import send_mail


@web.route('/register', methods=['GET', 'POST'])
def register():
    """
    用户注册
    :return:
    """
    form = RegisterForm(request.form)
    if request.method == 'POST' and form.validate():
        with db.auto_commit():
            user = User()
            user.set_attrs(form.data)
            db.session.add(user)
        return redirect(url_for('web.login'))
    return render_template('auth/register.html', form=form)


@web.route('/login', methods=['GET', 'POST'])
def login():
    """
    用户登陆
    :return:
    """
    form = LoginForm(request.form)
    if request.method == 'POST' and form.validate():
        user = User.query.filter_by(email=form.email.data).first()
        if user and user.check_password(form.password.data):
            # 返回用户登录票据并设置持续保存到cookie
            login_user(user, remember=True)
            next = request.args.get('next')
            # 防止重定向攻击（跳转地址是否以‘/’开头）
            if not next or not next.startswith('/'):
                next = url_for('web.index')
            return redirect(next)
        else:
            flash('账号或密码有误')

    return render_template('auth/login.html', form=form)


@web.route('/reset/password', methods=['GET', 'POST'])
def forget_password_request():
    """
    用户发送找回密码邮件
    :return:
    """
    form = EmailForm(request.form)
    if request.method == 'POST' and form.validate():
        account_email = form.email.data
        user = User.query.filter_by(email=account_email).first_or_404()
        # 发送邮件
        send_mail(
            account_email,
            '重置你的密码', 'email/reset_password.html',
            user=user,
            token=user.generate_token()
        )
        flash('一款邮件已经发送到你的邮箱' + account_email + ',请及时查收')
    return render_template('auth/forget_password_request.html', form=form)


@web.route('/reset/password/<token>', methods=['GET', 'POST'])
def forget_password(token):
    """
    跳转至
    :param token:
    :return:
    """
    form = ResetPasswordForm(request.form)
    if request.method == 'POST' and form.validate():
        if User.reset_password(token, form.password1.data):
            flash('密码重置成功，请使用新密码登录')
            return redirect(url_for('web.login'))
        else:
            flash('密码重置失败')
    return render_template('auth/forget_password.html', form=form)


@web.route('/change/password', methods=['GET', 'POST'])
def change_password():
    pass


@web.route('/logout')
def logout():
    """
    注销
    :return:
    """
    logout_user()
    return redirect(url_for('web.index'))
